from django import forms
from django.forms import ValidationError
from blog.models import UserInfo


class RegForm(forms.Form):
    username = forms.CharField(
        max_length=32,
        label='用户名',
        error_messages={
            'required': '用户名不能为空',
            'max_length': '用户名最长16位'
        },
        widget=forms.widgets.TextInput(
            attrs={'class': 'form-control'}
        )
    )

    password = forms.CharField(
        min_length=6,
        label='密码',
        widget=forms.widgets.PasswordInput(
            attrs={'class': 'form-control'}
        ),
        error_messages={
            'min_length': '密码至少6位',
            'required': '密码不能为空',
        }
    )

    re_password = forms.CharField(
        min_length=6,
        label='确认密码',
        widget=forms.widgets.PasswordInput(
            attrs={'class': 'form-control'}
        ),
        error_messages={
            'min_length': '密码至少6位',
            'required': '密码不能为空',
        }
    )

    email = forms.EmailField(
        label='邮箱',
        widget=forms.widgets.EmailInput(
            attrs={'class': 'form-control'}
        ),
        error_messages={
            'invalid': '邮箱格式不正确'
        }
    )

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if UserInfo.objects.filter(email=email).count():
            raise ValidationError('邮箱已经存在')
        return email

    def clean_username(self):
        username = self.cleaned_data.get('username')
        # 判断用户名和邮箱是否已经存在
        if UserInfo.objects.filter(username=username).count():
            raise ValidationError('用户名已经存在')
        return username

    def clean(self):
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')

        if password != re_password:
            self.add_error('re_password',ValidationError('两次密码输入不一致'))

        return self.cleaned_data
